﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QGraphicsPixmapItem>
#include <QImageReader>
#include <QStyleOptionGraphicsItem>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    statusLabel.resize(200,30);
    statusLabel.setText("coordinate:");
    ui->statusbar->addPermanentWidget(&statusLabel);

    // 关联信号和信号槽
    connect(ui->graphicsView,&QMyGraphicsView::updateItemPos,this,&MainWindow::updateItemPos);
    connect(ui->graphicsView,&QMyGraphicsView::transformview,this,&MainWindow::transformview);
    connect(ui->graphicsView,&QMyGraphicsView::sendcrossitempos,this,&MainWindow::setcrossitempos);
    connect(ui->graphicsView,&QMyGraphicsView::sendcrossitemselect,this,&MainWindow::setcrossitemselect,Qt::UniqueConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_openbutton_clicked()
{
    if (img!=nullptr)
    {
        delete img;
        img=nullptr;
    }

    // 读取图片
    img=new QImage;
    QString filepath=":/image/picture.jpg";
    if(filepath.isEmpty())
        return;
    else
    {
        // 尝试加载图像,如果图像加载不成功
        if (! img->load(filepath))
        {
            // 按照文件实际格式读取
            QImageReader reader;
            reader.setDecideFormatFromContent(true);
            reader.setFileName(filepath);

            // 仍然无法加载图像
            if (!reader.read(img))
            {
                // 判断文件是否可以读取
                if (reader.canRead())
                {
                    // 错误类型:Qt无法识别的图片类型,建议尝试使用OpenCV读取/非图片格式
                    QString strError = reader.errorString();
                    QMessageBox::information(this,"Open Image Error",strError);
                }
                else
                {
                    // 错误类型:无法读取文件/路径不存在
                    QString strError = reader.errorString();
                    QMessageBox::information(this,"Open Image Error",strError);
                }
                return;
            }
            // 载入的图像为空
            else if (img->isNull())
            {
                QMessageBox::information(this,"Open Image Error","This is a null image.");
                return;
            }
        }
    }

    if (MyPixmapItem!=nullptr)  {   delete MyPixmapItem;    MyPixmapItem=nullptr;}
    //将图片转为图元
    MyPixmapItem=new QGraphicsPixmapItem(QPixmap::fromImage(*img));
    MyPixmapItem->setPos(-MyPixmapItem->pixmap().width()/2,-MyPixmapItem->pixmap().height()/2);
    MyPixmapItem->setAcceptHoverEvents(true);//设置图元可以接收悬停事件

    if (scene1!=nullptr)
    {
        if (! QMyCrossItemlist.isEmpty())
        {
            scene1->destroyItemGroup(ItemGroup);
            QList<QGraphicsItem *> selectitemList_l=ui->graphicsView->items();
            for (int i = 0; i <selectitemList_l.size()-1; i++)
            {
                QMyCrossItemlist.removeOne(selectitemList_l[i]);
                scene1->removeItem(selectitemList_l[i]);
                delete selectitemList_l[i];
                selectitemList_l[i]=nullptr;
            }
        }

        scene1->clear();
        delete scene1;
        scene1=nullptr;
    }

    scene1=new QGraphicsScene;
    //将图元载入场景
    scene1->addItem(MyPixmapItem);

    //关联自定义视图和场景
    ui->graphicsView->setScene(scene1);
    ui->graphicsView->show();
}

// 更新平移,旋转,缩放
void MainWindow::transformview(QPointF translation,qreal rotation,qreal scaling)
{
    if (MyPixmapItem==nullptr) return;
    MyPixmapItem->moveBy(translation.x(),translation.y());
    MyPixmapItem->setRotation(rotation);

    if (ItemGroup!=nullptr)
        ItemGroup->moveBy(translation.x(),translation.y());
}

// 更新状态栏
void MainWindow::updateItemPos(QPointF pos)
{
    QString str = QString("coordinate: ") + "(" + QString::number(pos.x(),'f',2) + "," + QString::number(pos.y(),'f',2) + ")";
    statusLabel.setText(str);
}

// 添加自定义十字丝图元
void MainWindow::setcrossitempos(QPointF pos)
{
    MyCrossItem=new QMyCrossItem;
    connect(ui->graphicsView,&QMyGraphicsView::sendcrossitemscale,MyCrossItem,&QMyCrossItem::setitemscale,Qt::UniqueConnection);
    MyCrossItem->setPos(pos);
    QMyCrossItemlist.append(MyCrossItem);

    QList<QGraphicsItem *> selectitemList_l=ui->graphicsView->items();
    int sizes=selectitemList_l.size();

    /*
    for (int i=0;i<QMyCrossItemlist.size();i++)
    {
        scene1->removeItem(selectitemList_l[i]);
    }
    scene1->removeItem(selectitemList_l[sizes-2]);
    delete selectitemList_l[sizes-2];
    */

    ItemGroup=scene1->createItemGroup(QMyCrossItemlist);
    selectitemList_l=ui->graphicsView->items();
    sizes=selectitemList_l.size();

    if (sizes>3)
    {
        scene1->removeItem(selectitemList_l[sizes-2]);
        delete selectitemList_l[sizes-2];
        selectitemList_l[sizes-2]=nullptr;
    }
    selectitemList_l=ui->graphicsView->items();
    sizes=selectitemList_l.size();

    scene1->update();
}

// 删除框选区域内的十字丝
void MainWindow::setcrossitemselect(QRect NewRect)
{
    if (scene1==nullptr)    return;
    if (ItemGroup==nullptr) return;

    scene1->destroyItemGroup(ItemGroup);
    QList<QGraphicsItem *> selectitemList=ui->graphicsView->items(NewRect);
    QList<QGraphicsItem *> selectitemList_l=ui->graphicsView->items();
   // QList<QGraphicsItem *> QMyCrossItemlist_after=QMyCrossItemlist;

    int num=selectitemList.size();
    if (num>1)
        for (int i = 0; i <num-1; i++)
        {
            /*标记为选中状态
            QMyCrossItem *thisitem=(QMyCrossItem *)selectitemList[i];
            thisitem->setselcetype(true);
            */
            QMyCrossItemlist.removeOne(selectitemList[i]);
            scene1->removeItem(selectitemList[i]);
            delete selectitemList[i];
            selectitemList[i]=nullptr;

            if (QMyCrossItemlist.isEmpty())
            {
                ItemGroup=nullptr;
                return;
            }
        }
    //selectitemList_l=ui->graphicsView->items();

    ItemGroup=scene1->createItemGroup(QMyCrossItemlist);
    scene1->update();

    //selectitemList_l=ui->graphicsView->items();
}
